<?php
/**
 *  Created by: PhpStorm
 *  Author: 式神(vashi)<289650682@qq.com>
 *  Date: 2022-05-19
 *  Time: 15:44
 *  File: Crypt.php
 */
declare (strict_types=1);

namespace app\common\lib\tools;

class Crypt
{
    static protected $secureKey = 'VASHI_STEVEN';
    /**
     * 设置加密密钥
     *
     * @param string $key
     *
     * @return string
     */
    static public function key(string $key = ''): string
    {
        $sha1Key = $key ?: self::$secureKey;
        self::$secureKey=sha1($sha1Key);
        return base64_decode(hash('sha256', self::$secureKey, true));
    }

    /**
     * 加密
     * @param string $input     加密字符
     * @param string $secureKey 加密key
     * @return string
     */
    static public function encrypt(string $input, string $secureKey = ''): string
    {
        $encrypt = openssl_encrypt(
            $input,
            'aes-256-cbc',
            self::key($secureKey),
            OPENSSL_RAW_DATA,
            substr(self::$secureKey, -16)
        );
        return base64_encode($encrypt);
    }

    /**
     * 解密
     *
     * @param string $input     解密字符
     * @param string $secureKey 加密key
     *
     * @return string
     */
    static public function decrypt(string $input, string $secureKey = ''): string
    {
        $encrypted = base64_decode($input);
        return openssl_decrypt(
            $encrypted,
            'aes-256-cbc',
            self::key($secureKey),
            OPENSSL_RAW_DATA,
            substr(self::$secureKey, -16)
        );
    }
}